package yto.freemarker.springcloud.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 请求头传递
 *
 * @author dongxing
 **/
@Component
public class FeignTokenInterceptor implements RequestInterceptor {

    private final static String NAME = "oauthToken";

    @Override
    public void apply(RequestTemplate requestTemplate) {

        if (getHttpServletRequest() == null) {
            return;
        }
        requestTemplate.header(FeignTokenInterceptor.NAME, getHeaders(getHttpServletRequest(), FeignTokenInterceptor.NAME));
    }

    private HttpServletRequest getHttpServletRequest() {
        try {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (Exception e) {
            return null;
        }
    }

    private String getHeaders(HttpServletRequest httpServletRequest, String name) {
        if (httpServletRequest == null) {
            return "";
        }
        return httpServletRequest.getHeader(name);

    }
}
